// More info on Webpack's Node API here: https://webpack.github.io/docs/node.js-api.html
// Allowing console calls below since this is a build file.
/*eslint-disable no-console */
import webpack from 'webpack';
import 'colors';
import { argv as args } from 'yargs';
var fs= require('fs');
const fsExtra = require('fs-extra');
import async from 'async';

import webpackConfigs from '../webpack/webpack.config.server';

const allCallback = (err, stats, config) => {
  const inSilentMode = args.s; // set to true when -s is passed on the command

  if (!inSilentMode) {
    console.log('Generating minified bundle for production use via Webpack...'.bold.blue);
  }

  if (err) { // so a fatal error occurred. Stop here.
    console.log(err.bold.red);

    return 1;
  }

  const jsonStats = stats.toJson();

  if (jsonStats.hasErrors) {
    return jsonStats.errors.map(error => console.log(error.red));
  }

  if (jsonStats.hasWarnings && !inSilentMode) {
    console.log('Webpack generated the following warnings: '.bold.yellow);
    jsonStats.warnings.map(warning => console.log(warning.yellow));
  }

  if (!inSilentMode) {
    console.log(`Webpack stats: ${stats}`.green);
  }

  // if we got this far, the build succeeded.
  console.log(`Your app has been compiled in production mode for entry ${Object.keys(config.entry)} and written to ${config.output.path}. It\\'s ready to roll!`.green.bold);

  return 0;
};

// webpack(webpackConfigs).run((err, stats) => {
//     callback(err, stats, webpackConfigs);
// });
async.eachSeries(webpackConfigs, function(config,callback) {
  webpack(config).run((err, stats) => {
      allCallback(err, stats, config);
      callback();
  });
},function () {
    var newMaster = `${__dirname}/../server/public/masterBak`;
    var oldMaster = `${__dirname}/../server/public/master`;
    fs.exists(newMaster, function (flag) {
        if(flag){
            console.log('bulid master success!!!!');
            fsExtra.remove(oldMaster, function(err) {
                if (err) return console.error(err);
                fsExtra.move(newMaster, oldMaster, function(err) {
                    if (err) return console.error(err)
                    console.log("move file success!")
                    fsExtra.remove(newMaster, function(err) {
                        if (err) return console.error(err)
                        console.log("remove bak success!")
                    })
                });
            })
        }else{
            console.error('bulid master error -_-!')
        }
    })
});